﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace RockBus.DataContracts
{
    [DataContract(Namespace = StringConstants.RockBusNamespace)]
    public class PublisherConfiguration : EvaluatorConfigurationBase<PublisherInfo, ReceivePortInfo, ReceivePortDetail>
    {
        private static readonly Lazy<PublisherConfiguration> _empty = new Lazy<PublisherConfiguration>(() => { return new PublisherConfiguration(); }, true);
        public static PublisherConfiguration Empty { get { return _empty.Value; } }

        public PublisherConfiguration()
            : base()
        {
        }

        public PublisherConfiguration(IEnumerable<PublisherInfo> publishers)
            : base(publishers)
        {
        }

        public PublisherConfiguration(params PublisherInfo[] publishers)
            : this((IEnumerable<PublisherInfo>)publishers)
        {
        }

        public bool TryFindReceivePortInfo(PublisherReceivePortInfo prpi, out ReceivePortInfo rpi)
        {
            return this.TryFindReceivePortInfo(prpi.PublisherId, prpi.ReceivePortId, out rpi);
        }

        public bool TryFindReceivePortInfo(string publisherId, string receivePortId, out ReceivePortInfo rpi)
        {
            rpi = null;

            PublisherInfo pi = null;
            if (!this.EvaluationElementDictionary.TryGetValue(publisherId, out pi))
            {
                return false;
            }

            if (!pi.InfoDictionary.TryGetValue(receivePortId, out rpi))
            {
                return false;
            }

            return (rpi != null);
        }

        public bool TryFindReceivePortInfo(string absolutePath, out ReceivePortInfo rpi)
        {
            rpi = null;

            foreach (var publisher in this.EvaluationElementDictionary.Values.ToArray())
            {
                foreach (var rpi1 in publisher.InfoDictionary.Values.ToArray())
                {
                    if (absolutePath.EndsWith(rpi1.ReceiveEndpointInfo.Address))
                    {
                        rpi = rpi1;
                        return true;
                    }
                }
            }

            return (rpi != null);
        }
    }
}